package it.uniroma2.tesi.bellomaria;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utility {

	private static int indexRestart = 0;

	// metodo che ripulisce il codice XML dai caratteri speciali
	public static String cleanXML(String str) {

		// pulizia dai caratteri speciali xml
		String sourcestring = str;
		Pattern re = Pattern.compile("&lt;");
		Matcher m = re.matcher(sourcestring);
		String cleaned = m.replaceAll("<");

		re = Pattern.compile("&gt;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll(">");

		re = Pattern.compile("\n"); 
		m = re.matcher(cleaned); 
		cleaned = m.replaceAll("");
		
		re = Pattern.compile("\r"); 
		m = re.matcher(cleaned); 
		cleaned = m.replaceAll("");

		re = Pattern.compile("'");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("\\\\'");

		// per inserire nello script \': non vede l'apostrofo come carattere di chiusura.
		re = Pattern.compile("&apos;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("\\\\'"); 

		re = Pattern.compile("&quot;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("\"");

		re = Pattern.compile("&amp;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("");

		// pulizia dai caratteri accentati
		re = Pattern.compile("&agrave;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("à");

		re = Pattern.compile("&egrave;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("è");

		re = Pattern.compile("&eacute;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("é");

		re = Pattern.compile("&igrave;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("ì");

		re = Pattern.compile("&ograve;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("ò");

		re = Pattern.compile("&ugrave;");
		m = re.matcher(cleaned);
		cleaned = m.replaceAll("ù");

		System.out.println("Codice xml ripulito.");
		return cleaned;
	}

	// metodo che restituisce la stringa della lunghezza indicata a partire dal delimitatore.
	public static String getSubstring(String text, String pattern, int lenght) {
		/* text = testo in cui cercare, pattern = delimitatore, lenght = numero
		 * di caratteri da restituire.
		 */
		String result = null;
		int index = text.indexOf(pattern);

		if (index >= 0) {
			int initIndex = index + pattern.length();
			result = text.subSequence(initIndex, initIndex + lenght).toString();
		}
		return result;
	}
	
	// metodo che restituisce la stringa contenuta fra le due usate come delimitatori.
	public static String getSubstring(String text, String pattern, String endpattern, Boolean restart) {
		/*
		 * text = testo in cui cercare, pattern = delimitatore iniziale,
		 * endpattern = delimitatore finale
		 */
		String result = null;
		int index = 0;
		if (restart)
			index = text.indexOf(pattern, indexRestart);
		else
			index = text.indexOf(pattern);

		int endIndex = text.indexOf(endpattern, index);

		if (index >= 0 && endIndex >= 0) {
			int initIndex = index + pattern.length();
			result = text.subSequence(initIndex, endIndex).toString();
			if (restart)
				indexRestart = endIndex + endpattern.length();
		}
		return result;
	}


	// metodo che effettua la scrittura su file in utf-8.
	public static void writeUtf8(String str, String outputPath, boolean rewrite) {
		File f = new File(outputPath);
		if(!rewrite)
			if(f.exists()){
				System.out.println("Il file ["+outputPath+"] già esiste. Rimuovere la vecchia copia prima di procedere.");
				System.exit(0);
			}
			
		try {
			FileOutputStream fos = new FileOutputStream(outputPath);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			PrintWriter out = new PrintWriter(osw);
			System.out.println("Scrittura file : " + outputPath+ " con codifica : " + osw.getEncoding());
			out.write(str);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void resetInedex(){
		indexRestart = 0;
	}
	
	// metodo che carica il contenuto del file rss in una stringa.
	public static String fileToString(String fileName) throws FileNotFoundException {

		String rss = null;
		File f = new File(fileName);
		FileInputStream file = null;
		StringBuffer buffer = null;
		InputStreamReader isr = null;
		BufferedReader in = null;

		try {
			buffer = new StringBuffer();
			file = new FileInputStream(f);
			isr = new InputStreamReader(file, "UTF-8");
			in = new BufferedReader(isr);
			int ch;
			while ((ch = in.read()) > -1) {
				buffer.append((char) ch);
			}

			rss = buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				System.out.println("Errore nella chiusura del file.");
				e.printStackTrace();
			}
		}
		return rss;
	}

	// metodo che effettua la lettura della pagina web
	public static String readPage(String urlPage, String code) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		try {
			url = new URL(urlPage);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		try {
			URLConnection conn = url.openConnection();
			InputStreamReader isr = new InputStreamReader(conn.getInputStream(), code);
			BufferedReader in = new BufferedReader(isr);
			System.out.println("Lettura Pagina Web : "+urlPage+" con codifica : " + isr.getEncoding());
			int ch;
			while ((ch = in.read()) > -1) {
				buffer.append((char) ch);
			}
			in.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String cleanFilmTitle(String titolo){
		
		String t = titolo;
		int index = t.indexOf("-");
		if(index>=0){
			t = t.substring(0, index);
		}
		
		Pattern re = Pattern.compile(" in 3D");
		Matcher m = re.matcher(t);
		t = m.replaceAll("");
		
		re = Pattern.compile("3D");
		m = re.matcher(t);
		t = m.replaceAll("");

		return t;
	}
	
	// metodo che sostituisce i tag html presenti nelle trame con spazi bianchi.
	public static String cleanTrama(String str) {
		String cleanedTrama = str;
		String link = null;
		while (true) {
			link = Utility.getSubstring(cleanedTrama, "<", ">", false);
			if (link!=null){
				cleanedTrama = cleanedTrama.replace("<"+link+">", "");
			}else
				break;
		}
		return cleanedTrama;
	}
	
	public static String getScriptPath(String mode){

		String scriptPath = null; 

		if(mode.equals("create"))
			scriptPath = RssParser.pathLavoro+"/script";
		else
			scriptPath = RssParser.pathLavoro+"/script/"+ RssParser.dataElaborazione; 
				
		File f = new File(scriptPath);

		if(!f.isDirectory())
			if(!f.mkdir()){
				System.out.println("creazione della directory["+RssParser.pathLavoro+"/script/"+ RssParser.dataElaborazione +"] non riuscita. Verificare se si possiedono le grant");
				System.exit(0);
			}
						
		return scriptPath;
	}
}
